package com.stn.zjx.givingtreasure.activity.realauth;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.makeramen.roundedimageview.RoundedImageView;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.FileUploadDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.FileNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserRealAuthNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.Base64FileUtils;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxImageTool;
import com.vondear.rxtools.RxPhotoTool;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class UserRealAuthActivity extends BaseActivity {
    private static final int PRC_PHOTO_PICKER = 1001;

    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.go_real)
    Button goReal;
    @BindView(R.id.up_positive_iv)
    RoundedImageView upPositiveIv;
    @BindView(R.id.up_positive)
    LinearLayout upPositive;
    @BindView(R.id.up_side_iv)
    RoundedImageView upSideIv;
    @BindView(R.id.up_side)
    LinearLayout upSide;
    @BindView(R.id.name_edit)
    EditText nameEdit;
    @BindView(R.id.id_card_edit)
    EditText idCardEdit;
    @BindView(R.id.real_status_iv)
    ImageView realStatusIv;
    private String one_url = "";
    private String two_url = "";
    BottomDialog uploadDialog;

    public int imageType = 1;
    private Uri resultUri;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @SuppressLint("CheckResult")
    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.upload_real_photo));
        if (UserService.getInstance(this)
                .getOnlineLoginUser() == null) {
            return;
        }
        User user = UserService.getInstance(this)
                .getOnlineLoginUser();
        nameEdit.setText(user.getRealRealname());
        nameEdit.setSelection(nameEdit.getText().length());
        idCardEdit.setText(user.getRealIdcard());
        idCardEdit.setSelection(idCardEdit.getText().length());
        RequestOptions rp = new RequestOptions();
        rp.dontAnimate();
        rp.placeholder(new ColorDrawable(ActivityCompat.getColor(getApplicationContext(), R.color.light_gray)));
        if (!TextUtils.isEmpty(user.getRealCardface())) {
            one_url = user.getRealCardface();

            Glide
                    .with(UserRealAuthActivity.this)
                    .asBitmap()
                    .apply(rp)
                    .load(user.getRealCardface())
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            upPositiveIv.setImageBitmap(resource);
                        }
                    });
        }
        if (!TextUtils.isEmpty(user.getRealCardidentity())) {
            one_url = user.getRealCardidentity();
            Glide
                    .with(UserRealAuthActivity.this)
                    .asBitmap()
                    .apply(rp)
                    .load(user.getRealCardidentity())
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            upSideIv.setImageBitmap(resource);
                        }
                    });
        }
        goReal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(nameEdit.getText())) {
                    showToast(getString(R.string.please_input_real_name));
                    return;
                }
                if (TextUtils.isEmpty(idCardEdit.getText())) {
                    showToast(getString(R.string.please_input_id_card));
                    return;
                }
                if (TextUtils.isEmpty(one_url)) {
                    showToast(getString(R.string.please_up_front));
                    return;
                }
                if (TextUtils.isEmpty(two_url)) {
                    showToast(getString(R.string.please_up_slide));
                    return;
                }
                User userOnline = UserService.getInstance(UserRealAuthActivity.this).getOnlineLoginUser();
                if (userOnline == null) {
                    return;
                }
                UserRealAuthNetImpl
                        .up_real(userOnline.getToken(),
                                nameEdit.getText().toString().trim(),
                                idCardEdit.getText().toString().trim(),
                                one_url,
                                two_url,
                                "",
                                "up_real",
                                new StringCallback() {
                                    @Override
                                    public void onStart(Request<String, ? extends Request> request) {
                                        super.onStart(request);
                                        showLoading();
                                    }

                                    @Override
                                    public void onFinish() {
                                        super.onFinish();
                                        dissmissLoading();
                                    }

                                    @Override
                                    public void onSuccess(Response<String> response) {
                                        StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                        switch (domain.getStatus()) {
                                            case BaseApi.REQUEST_SUCCESS_CODE:
                                           //     showToast(domain.getMessage());
                                                finish();
                                                break;
                                            default:
                                                showToast(domain.getMessage());
                                                break;
                                        }
                                    }

                                });

            }
        });
        upPositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageType = 1;
                uploadDialog.show();
            }
        });
        upSide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageType = 2;
                uploadDialog.show();
            }
        });
        switch (user.getRealStatus()) {
            case 0:
                goReal.setClickable(true);
                goReal.setBackgroundResource(R.drawable.shape_blue_5dp);
                goReal.setText(getString(R.string.sure_upload));
                upPositive.setClickable(true);
                upSide.setClickable(true);
                nameEdit.setFocusable(true);
                nameEdit.setFocusableInTouchMode(true);
                idCardEdit.setFocusable(true);
                idCardEdit.setFocusableInTouchMode(true);
                realStatusIv.setVisibility(View.GONE);
                break;
            case 1:
                goReal.setClickable(false);
                goReal.setBackgroundResource(R.drawable.shape_darkgray_5dp);
                goReal.setText(getString(R.string.real_loading));
                upPositive.setClickable(false);
                upSide.setClickable(false);
                nameEdit.setFocusable(false);
                nameEdit.setFocusableInTouchMode(false);
                idCardEdit.setFocusable(false);
                idCardEdit.setFocusableInTouchMode(false);
                realStatusIv.setImageResource(R.mipmap.real_status_loading);
                realStatusIv.setVisibility(View.VISIBLE);
                break;
            case 2:
                goReal.setClickable(false);
                goReal.setBackgroundResource(R.drawable.shape_darkgray_5dp);
                goReal.setText(getString(R.string.real_success));
                upPositive.setClickable(false);
                upSide.setClickable(false);
                nameEdit.setFocusable(false);
                nameEdit.setFocusableInTouchMode(false);
                idCardEdit.setFocusable(false);
                idCardEdit.setFocusableInTouchMode(false);
                realStatusIv.setImageResource(R.mipmap.real_status_sucess);
                realStatusIv.setVisibility(View.VISIBLE);
                break;
            case 3:
                goReal.setClickable(true);
                goReal.setBackgroundResource(R.drawable.shape_blue_5dp);
                goReal.setText(getString(R.string.real_reload));
                upPositive.setClickable(true);
                upSide.setClickable(true);
                nameEdit.setFocusable(true);
                nameEdit.setFocusableInTouchMode(true);
                idCardEdit.setFocusable(true);
                idCardEdit.setFocusableInTouchMode(true);
                realStatusIv.setImageResource(R.mipmap.real_status_error);
                realStatusIv.setVisibility(View.VISIBLE);
                break;
        }
        uploadDialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_select_images)
                .setCancelOutside(false)
                .setDimAmount(0.4f)
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        v.findViewById(R.id.cancel)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadDialog.dismiss();

                                    }
                                });
                        v.findViewById(R.id.location_upload)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadDialog.dismiss();
                                        choicePhoto(1);
                                    }
                                });
                        v.findViewById(R.id.camera_upload)
                                .setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        uploadDialog.dismiss();
                                        choicePhoto(0);
                                    }
                                });
                    }
                });


    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void choicePhoto(int openType) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            switch (openType) {
                case 0:
                    RxPhotoTool.openCameraImage(this);
                    break;
                case 1:
                    RxPhotoTool.openLocalImage(this);
                    break;
            }

        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_real_auth);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                try {
                    Glide
                            .with(UserRealAuthActivity.this)
                            .asBitmap()
                            .load(data.getData())
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    Bitmap newbitmap = ToolsUtils.comp(resource);
                                    File new_file = new File(getCacheDir().getPath() + "/" + UUID.randomUUID().toString() + ".png");
                                    boolean is = RxImageTool.save(newbitmap, new_file, Bitmap.CompressFormat.PNG);
                                    if (is) {
                                        uploadAvatar(new_file);
                                    } else {
                                        showToast(getString(R.string.no_cache_data));
                                    }
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(e.getMessage());
                }

                //    initUCrop(data.getData(), false);
                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                try {
                    Glide
                            .with(UserRealAuthActivity.this)
                            .asBitmap()
                            .load(RxPhotoTool.imageUriFromCamera)
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    Bitmap newbitmap = ToolsUtils.comp(resource);
                                    File new_file = new File(getCacheDir().getPath() + "/" + UUID.randomUUID().toString() + ".png");
                                    boolean is = RxImageTool.save(newbitmap, new_file, Bitmap.CompressFormat.PNG);
                                    if (is) {
                                        uploadAvatar(new_file);
                                    } else {
                                        showToast(getString(R.string.no_cache_data));
                                    }
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(e.getMessage());
                }
                //  initUCrop(RxPhotoTool.imageUriFromCamera, false);
                break;
            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                resultUri = UCrop.getOutput(data);
                File file = new File(Objects.requireNonNull(RxPhotoTool.getImageAbsolutePath(this, resultUri)));


                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                assert cropError != null;
                showToast(cropError.getMessage());
                break;
        }
    }

    private void initUCrop(Uri uri, boolean isCircle) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);
        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));
        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".png"));
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.white));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.white));
        options.setToolbarWidgetColor(ActivityCompat.getColor(this, R.color.default_black));
        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);

        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
        options.setCircleDimmedLayer(isCircle);
        //设置是否展示矩形裁剪框
        options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    public void uploadAvatar(File file) {
        String base = Base64FileUtils.encryptToBase64(file.getAbsolutePath());
        JSONObject data = new JSONObject();
        try {
            data.put("upfileBase64Content", base);
            data.put("upfileName", "" + new Date().getTime());
            data.put("upfileSuffix", "png");
            data.put("upfiletype", "0");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        FileNetImpl
                .upload_base64_file(data.toString(), "upload_base64_file", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {


                        if (response.isSuccessful() && !isFinishing()) {
                            Gson gson = new Gson();
                            FileUploadDomain domain = gson.fromJson(response.body(), FileUploadDomain.class);
                            switch (domain.getStatus()) {
                                case BaseApi.REQUEST_SUCCESS_CODE:
                                    switch (imageType) {
                                        case 1:
                                            Glide.with(UserRealAuthActivity.this)
                                                    .load(file)
                                                    .apply(new RequestOptions().dontAnimate())
                                                    .into(new SimpleTarget<Drawable>() {
                                                        @Override
                                                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                                            upPositiveIv.setImageDrawable(resource);
                                                        }
                                                    });
                                            one_url = domain.getData().getPath();
                                            break;
                                        case 2:
                                            Glide.with(UserRealAuthActivity.this)
                                                    .load(file)
                                                    .apply(new RequestOptions().dontAnimate())
                                                    .into(new SimpleTarget<Drawable>() {
                                                        @Override
                                                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                                            upSideIv.setImageDrawable(resource);
                                                        }
                                                    });
                                            two_url = domain.getData().getPath();
                                            break;
                                    }

                                    break;
                                default:
                                    showToast(domain.getMessage());
                                    break;
                            }

                        }
                    }
                });

    }

}
